package com.sgl.controller;

import com.sgl.config.shiro.ShiroUtil;
import com.sgl.entity.OrderHistory;
import com.sgl.entity.User;
import com.sgl.entity.dto.EXportDto;
import com.sgl.service.DictService;
import com.sgl.service.OrderService;
import com.sgl.util.ExportExcelUtil;
import com.sgl.util.ExportExcelWrapper;
import com.sgl.util.PageBean;
import com.sgl.util.ReturnData;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 回调订单管理
 */
@RestController
@RequestMapping("/sgl/order")
public class BgOrderController {
    @Autowired
    OrderService orderService;

    @Autowired
    DictService dictService;



    @RequestMapping("findList")
    public ReturnData findList(PageBean<OrderHistory> pageBean, String merOrderId, String orderId,Float minPrice,Float maxPrice,Integer status,String mt5Number,String bgTime,String edTime) throws ParseException, TemplateModelException {
        HashMap<String, Object> param = new HashMap<String, Object>();
        User user= ShiroUtil.getUser();
        if (status!=null){
            param.put("status", status);
        }
        if (minPrice!=null&&maxPrice!=null){
            param.put("minPrice", minPrice);
            param.put("maxPrice", maxPrice);
        }else if (minPrice==null&&maxPrice!=null){
            param.put("maxPrice", maxPrice);
        }else if (minPrice!=null&&maxPrice==null){
            param.put("minPrice", minPrice);
        }else if (mt5Number!=null){
            param.put("mt5Number", mt5Number);
        }

        if (bgTime!=null&&""!=bgTime){
            Date bgDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(bgTime);
            param.put("bgTime",bgDate);
            if (edTime==null){
                param.put("edTime",new Date());
            }
        }if (edTime!=null&&""!=edTime){
            Date edDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(edTime);
            param.put("edTime",edDate);
            if (null==bgTime||""==bgTime||StringUtils.isBlank(bgTime)){
                return new ReturnData().failBack("开始日期不能为空");
            }
        }

        /*if (user.getRole()==1){
//            String begin=dictService.findByKeywords("generalAdministrator").getValue();
            Integer end=Integer.valueOf(dictService.findByKeywords("seniorAdministrator").getValue());
            param.put("end", end);
        }*/
        if(StringUtils.isNotBlank(merOrderId)) {
            param.put("merOrderId", merOrderId);
        }
        if(StringUtils.isNotBlank(orderId)) {
            param.put("orderId", orderId);
        }

        pageBean.setParam(param);
        List<OrderHistory> list = orderService.findList(pageBean);
        int count = orderService.countList(pageBean);
        pageBean.setContent(list);
        pageBean.setTotalCount(count);
        return new ReturnData().okBack(pageBean);
    }

    @PostMapping("/add")
    public ReturnData add(OrderHistory orderHistory){
        ReturnData rd = new ReturnData();
        int count = orderService.inserOrders(orderHistory);
        if(count > 0) {
            return rd.okBack();
        }
        return rd.failBack();
    }

    @PostMapping("/update")
    public ReturnData update(OrderHistory orderHistory){
        ReturnData rd = new ReturnData();
        int count = orderService.update(orderHistory);
        if(count > 0) {
            return rd.okBack();
        }
        return rd.failBack();
    }

    @RequestMapping("/delete")
    public ReturnData delete(String ids) {
        ReturnData rd = new ReturnData();
        if(StringUtils.isBlank(ids)) {
            return rd.failBack("请选择要删除的内容");
        }
        int rs =orderService.delete(Arrays.asList(ids.split(",")));
        if (rs==0){
            return rd.failBack("没有删除任何内容");
        }
        return rd.okBack("共删除"+rs+"条记录");
    }

    @RequestMapping("/get/excel")
    public ReturnData  getExcel(HttpServletRequest request,HttpServletResponse response,PageBean<OrderHistory> pageBean,String merOrderId, String orderId,Float minPrice,Float maxPrice,Integer status,String mt5Number,String bgTime,String edTime) throws Exception {
        // 准备数据
        HashMap<String, Object> param = new HashMap<String, Object>();
        User user= ShiroUtil.getUser();
        if (status!=null){
            param.put("status", status);
        }
        if (minPrice!=null&&maxPrice!=null){
            param.put("minPrice", minPrice);
            param.put("maxPrice", maxPrice);
        }else if (minPrice==null&&maxPrice!=null){
            param.put("maxPrice", maxPrice);
        }else if (minPrice!=null&&maxPrice==null){
            param.put("minPrice", minPrice);
        }else if (mt5Number!=null&&""!=mt5Number){
            param.put("mt5Number", mt5Number);
        }
        if (bgTime!=null&&""!=bgTime){
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(bgTime);
            param.put("bgTime",date);
            if (edTime==null){
                param.put("edTime",new Date());
            }
        }if (edTime!=null&&""!=edTime){
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(edTime);
            param.put("edTime",date);
            if (null==bgTime||""==bgTime||StringUtils.isBlank(bgTime)){
                return new ReturnData().failBack("开始日期不能为空");
            }
        }
        if (user.getRole()==1){
//            String begin=dictService.findByKeywords("generalAdministrator").getValue();
            Integer end=Integer.valueOf(dictService.findByKeywords("seniorAdministrator").getValue());
            param.put("end", end);
        }
        if(StringUtils.isNotBlank(merOrderId)) {
            param.put("merOrderId", merOrderId);
        }
        if(StringUtils.isNotBlank(orderId)) {
            param.put("orderId", orderId);
        }
        pageBean.setParam(param);
        List<OrderHistory> list = orderService.findList(pageBean);
        List<EXportDto> dtos = new ArrayList<>();
        for (OrderHistory item:list){
            EXportDto dto = new EXportDto();
            dto.setP1(item.getMerchantId());
            dto.setP2(item.getMerOrderId());
            dto.setP3(item.getOrderId());
            dto.setP4(item.getMt5Number());
            dto.setP5(item.getNoticeAmount());
            if (item.getStatus()==0){
                dto.setP6("未入金完成");
            }else if (item.getStatus()==1){
                dto.setP6("入金完成");
            }else if (item.getStatus()==2){
                dto.setP6("回调失败正在重复回调");
            }else if (item.getStatus()==3||item.getStatus()==4||item.getStatus()==5){
                dto.setP6("待管理员审核");
            }
            dto.setP7(item.getCreateTime());
            dto.setP8(item.getAcceptTime());
            dto.setP10(item.getCoinNum());
            String verifyUser = item.getVerifyUser();
            if (null==verifyUser||""==verifyUser){
                dto.setP9("自动入金");
            }else{
                dto.setP9(verifyUser);
            }
            dtos.add(dto);
        }
       /* PageBean<EXportDto> bean = new PageBean<>();
        bean.setContent(dtos);
        return new ReturnData().okBack(bean);*/
        //ExportExcelUtil<EXportDto> util = new ExportExcelUtil<>();
        ExportExcelWrapper<EXportDto> util = new ExportExcelWrapper<>();
        String[] columnNames = {"商户号","CRM订单号","支付系统订单号","MT5账号","金额($)","收币数量","订单状态","下单时间","接收时间","审核人"};
        Date date = new Date();
        SimpleDateFormat sfd = new SimpleDateFormat("MM-dd_HH:mm");
        String format = sfd.format(date);
        //Date accessTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeStr1);
        util.exportExcel("入金订单_"+format, "入金订单", columnNames, dtos, response, ExportExcelUtil.EXCEL_FILE_2003);
        return new ReturnData().okBack("您好:"+ShiroUtil.getUser().getBgLoginName()+"导出数据表成功");
    }

}
